<?php
require("bases.php");

class index extends bases
{

    public function __construct()
    {
        parent::__construct();
        try {

        } catch (Exception $e) {

        }
    }

    public function index()
    {
        try {
            $redata = array();
            $postdata = $this->spArgs();
            $obj_course_time = spClass('course_time');
            $obj_order_record = spClass('order_record');
            $obj_school_weeks = spClass('school_week');
            $obj_cato_course = spClass("cato_course");
            //传过来的预约的目录，课程，实验
            $testid = $postdata["testid"];
            $courseid = $postdata["courseid"];
            $cataid = $postdata["cataid"];
            if(!$testid || !$courseid || !$cataid)
                throw new Exception("预约的必要参数丢失");
            //若未填，则默认当天
            if(!$postdata['current_date'] || $postdata['current_date'] == ''){
                $postdata['current_date'] = date('Y-m-d',time());
            }
            //获取全部课节
            $course_time_rs = $obj_course_time ->findAll(array('status'=>1, 'isdel'=>0),null,'id,name,course_time');
            $course_time_rs = array_column($course_time_rs, null,'id');
            //获取当天时间的教学周
            $current_date = date('Y-m-d',time());
            $current_school_week = $obj_school_weeks->find(array('status'=>1, 'isdel'=>0,'starttime <=' => $current_date, 'endtime >=' => $current_date ));
            //获取当天的下两个教学周
            $condition = " starttime > '" . $current_school_week['endtime'] ."' and status = 1 and isdel = 0";
            $res = $obj_school_weeks->findAll($condition, "starttime asc", "", null, 2);
            //设定查找起始时间，开始时间为下一个教学周的开始时间，结束时间是下下个教学周的结束时间
            $allowed_end_time = strtotime($res[1]['endtime']) + 60 * 60 * 24 - 1;
            $allowed_start_time = strtotime($res[0]['starttime']);
            //查找当天的所有预定和关闭记录
            $where = " days = '". $postdata['current_date']. "'";
            $order_record_rs = $obj_order_record->findAll($where);
            //开始判断是否可预约
            if(strtotime($postdata['current_date']) > $allowed_end_time ){
                //如果判断时间是两周之后，不允许预约
                foreach ($course_time_rs as $k =>&$v){
                    $v['mark'] = "two week later";
                    $v['status'] = 2;
                    $v['statusText'] = '不可预约';
                    $v['statusAlter'] = '仅可预约当前算起的后两个教学周';
                }
                unset($v);
            }elseif(strtotime($postdata['current_date']) < strtotime($current_school_week['starttime'])){
                //如果判断时间是当前周之前，标明已经过去
                foreach ($course_time_rs as $k =>&$v){
                    $condition = "days = '{$postdata["current_date"]}' and find_in_set('{$v["id"]}', time) and find_in_set('$cataid', cato_id) and isdel = 0";
                    if($record_rs = $obj_order_record->find($condition)){
                        if($record_rs["status"] == 1){
                            //被占用
                            if($record_rs["student_id"] == $this->login_rs["id"]){
                                //自己占用
                                $course_rs = $obj_cato_course->find(array("id"=>$record_rs["test_id"]));
                                $v['mark'] = "before";
                                $v['status'] = 3;
                                $v['statusText'] = $course_rs["name"];
                                $v['statusAlter'] = '已预约';
                            }else{
                                //他人占用
                                $v['mark'] = "before";
                                $v['status'] = 2;
                                $v['statusText'] = '被占用';
                                $v['statusAlter'] = '当前课节已被占用';
                            }
                        }else{
                            //被关闭
                            $v['mark'] = "before";
                            $v['status'] = 2;
                            $v['statusText'] = '已关闭';
                            $v['statusAlter'] = '当前课节对应的目录已被管理员关闭';
                        }
                    }else{
                        $v['mark'] = "before";
                        $v['status'] = 2;
                        $v['statusText'] = '不可预约';
                        $v['statusAlter'] = '仅可预约当前算起的后两个教学周';
                    }
                }
                unset($v);
            }elseif(
                strtotime($postdata['current_date']) <= strtotime($current_school_week['endtime'])
                &&
                strtotime($postdata['current_date']) >= strtotime($current_school_week['starttime'])
            ){
                //表名当前周
                foreach ($course_time_rs as $k =>&$v){
                    $condition = "days = '{$postdata["current_date"]}' and find_in_set('{$v["id"]}', time) and find_in_set('$cataid', cato_id) and isdel = 0";
                    if($record_rs = $obj_order_record->find($condition)){
                        if($record_rs["status"] == 1){
                            //被占用
                            if($record_rs["student_id"] == $this->login_rs["id"]){
                                //自己占用
                                $course_rs = $obj_cato_course->find(array("id"=>$record_rs["test_id"]));
                                $v['mark'] = "nowweek";
                                $v['status'] = 3;
                                $v['statusText'] = $course_rs["name"];
                                $v['statusAlter'] = '已预约';
                            }else{
                                //他人占用
                                $v['mark'] = "nowweek";
                                $v['status'] = 2;
                                $v['statusText'] = '被占用';
                                $v['statusAlter'] = '当前课节已被占用';
                            }
                        }else{
                            //被关闭
                            $v['mark'] = "nowweek";
                            $v['status'] = 2;
                            $v['statusText'] = '已关闭';
                            $v['statusAlter'] = '当前课节对应的目录已被管理员关闭';
                        }
                    }else{
                        $v['mark'] = "nowweek";
                        $v['status'] = 2;
                        $v['statusText'] = '不可预约';
                        $v['statusAlter'] = '仅可预约当前算起的后两个教学周';
                    }
                }
                unset($v);
            }elseif(
                strtotime($postdata['current_date']) >= $allowed_start_time
                &&
                strtotime($postdata['current_date']) <= $allowed_end_time
            ){
                //表名当前的下两个教学周
                foreach ($course_time_rs as $k =>&$v){
                    $condition = "days = '{$postdata["current_date"]}' and find_in_set('{$v["id"]}', time) "
                    ." and (student_id != ".$this->login_rs["id"]." and find_in_set('$cataid', cato_id) or student_id = ".$this->login_rs["id"].")"
                    ." and isdel = 0";
                    if($record_rs = $obj_order_record->find($condition)){
                        if($record_rs["status"] == 1){
                            //被占用
                            if($record_rs["student_id"] == $this->login_rs["id"]){
                                //自己占用
                                $course_rs = $obj_cato_course->find(array("id"=>$record_rs["test_id"]));
                                $v['mark'] = "two week in";
                                $v['status'] = 3;
                                $v['statusText'] = $course_rs["name"];
                                $v['statusAlter'] = '已预约';
                                //$v['sql'] = $condition;
                            }else{
                                //他人占用
                                $v['mark'] = "two week in";
                                $v['status'] = 2;
                                $v['statusText'] = '被占用';
                                $v['statusAlter'] = '当前课节已被占用';
                                //$v['sql'] = $condition;
                            }
                        }else{
                            //被关闭
                            $v['mark'] = "two week in";
                            $v['status'] = 2;
                            $v['statusText'] = '已关闭';
                            $v['statusAlter'] = '当前课节对应的目录已被管理员关闭';
                        }
                    }else{
                        $v['mark'] = "two week in";
                        $v['status'] = 1;
                        $v['statusText'] = "立即预约";
                        $v['statusAlter'] = '确认预约当前时间吗';
                    }
                }
                unset($v);
            }
            //$course_time_rs = $this->getClassesStatus($order_record_rs,$course_time_rs,$postdata,$is_current,$is_allowed,$is_pasted);
            $redata['course_time_rs'] = $course_time_rs;
            $this->returnApi($redata);
        }catch (Exception $e) {
            echo json_encode(array("data" => array(), "message" => $e->getMessage(), "code" => '0'));
            exit();
        }
    }

    /*
     * $orderRecordRs 查找当天的所有预定和关闭记录
     * $courseTimeRs 课节集合
     * $params 传输的参数
     * $is_current 是否是当前周
     * $is_allowed 是否是下两周
     * $is_pasted 是否是之前的周
     * */
    public function getClassesStatus($orderRecordRs,$courseTimeRs,$params,$is_current=0,$is_allowed=0,$is_pasted=0){
        $obj_cato_course = spClass('cato_course');
        $time_course_array = array();
        if(!empty($orderRecordRs)){
            foreach($orderRecordRs as $k => $v){
                if($v['time'] && !stripos($v['time'], ',') !== false){
                    $time_course_info = array(
                        'test_id' => $v['test_id'],
                        'cato_id' => $v['cato_id'],
                        'course_id' =>$v['course_id'],
                        'status' => $v['status'],
                        'student' => $v['student_id'],
                        'recordid' => $v['id']
                    );
                    //学生 当前目录的选课
                    if($v['cato_id']  ==  $params['cataid']){
                        $time_course_array[$v['time']][]  = $time_course_info;
                    }elseif($v['student_id'] == $this->login_rs['id'] && !stripos($v['cato_id'] , $params['cataid']) !== false){
                        $time_course_array[$v['time']][]  = $time_course_info;
                    }
                }else{
                    $admin_time = explode(',',$v['time']);
                    $time_course_info = array(
                        'test_id' => $v['test_id'],
                        'cato_id' => $v['cato_id'],
                        'course_id' =>$v['course_id'],
                        'student' => $v['student_id'],
                        'status' => $v['status'],
                        'recordid' => $v['id']
                    );

                    foreach($admin_time as $k1 =>$v1){
                        //管理员关闭当前目录课程
                        if(stripos($v['cato_id'] , $params['cataid']) !== false){
                            $time_course_array[$v1][] = $time_course_info;
                        }

                    }
                }
            }

            foreach ($courseTimeRs as $k1 => &$v1){
                $temp_data = $time_course_array[$k1];
                if($temp_data){
                    foreach ($temp_data as $k2 => $v2){
                        //判断管理员关闭状况
                        $order_course_info = $obj_cato_course -> find(array('id'=>$v2['test_id']));
                        if($v2['status'] == 2 ){
                            $v1['status'] = 2;
                            $v1['statusText'] = '管理员关闭';
                        }elseif($v2['status'] == 1){
                            //   占用 ==》 选中该课程
                            //   自己预约或者修改
                            if($v2['student'] == $this->login_rs['id']){
                                if($params['recordid'] && $params['recordid'] == $v2['recordid']){
                                    $v1['status'] =0;
                                    $v1['statusText'] = '修改时间 ';
                                }else{
                                    //当前目录 ，自己占用
                                    if($v['cato_id']  ==  $params['cataid']){
                                        $v1['status'] =1;
                                        $v1['statusText'] = $order_course_info['name'];
                                    }else{
                                        //费当前目录，自己该时间选过其他课程
                                        $v1['status'] =6;
                                        $v1['statusText'] = $order_course_info['name'];
                                    }


                                }
                            }else{
                                //别人占用
                                $v1['status'] = 8;
                                $v1['statusText'] = '他人占用';
                            }
                        }
                    }
                }else{
                    if(!$is_allowed){
                        $v1['status'] = 7;
                        $v1['statusText'] = '暂无选课';
                    }else{
                        $v1['status'] =0;
                        $v1['statusText'] = '立即预约';
                    }

                }
            }
        }else{
            foreach ($courseTimeRs as $k => &$v) {
                if(!$is_allowed){
                    $v['status'] =7;
                    $v['statusText'] = '暂无选课';
                }else{
                    $v['status'] =0;
                    $v['statusText'] = '立即预约';
                }

            }
        }
        return $courseTimeRs;
    }

    public function orderClasses(){
        try{
            $redata = array();
            $postdata = $this->spArgs();
            $obj_school_weeks = spClass('school_week');
            $obj_order_record = spClass('order_record');
            $time = time();
            //获取当前教学周
            $school_week_rs = $obj_school_weeks -> find(array('status'=>1,'isdel'=>0,'starttime <= ' => $postdata['select_date'], 'endtime >=' => $postdata['select_date']));
            //判断冲突  （1）时间冲突（该时间段该学生预约过其他课程）（2）其他人冲突 其他学生预约过同一目录下的课程
            $conflict_where_user = " days = '".$postdata['select_date']."'" . " and time = ". $postdata['time_id'] ." and student_id = ". $this->login_rs['id'];
            $conflict_user = $obj_order_record ->find($conflict_where_user);
            if($conflict_user)
                throw new Exception("您在这个时段选过其他课程");
            //其他用户有没有占用当前课节的目录
            $conflict_where_cato = " days = '".$postdata['select_date']."'" . " and time = ". $postdata['time_id'] ." and cato_id = ". $postdata['cataid'];
            $conflict_cato = $obj_order_record ->find($conflict_where_cato);
            if($conflict_cato)
                throw new Exception("其他人在这个时段内选过相同类型的课程");
            $data = array(
                'school_week_id'=> intval($school_week_rs['id']),
                'student_id' => $this->login_rs['id'],
                'days' => date('Y-m-d', strtotime($postdata['select_date'])),
                'time' => $postdata['time_id'],
                'cato_id' => $postdata['cataid'],
                'course_id' => $postdata['courseid'],
                'test_id' => $postdata['testid'],
                'order_starttime' => $time,
                'order_endtime' =>$time + 60*60*24,
                'status' => 1,
            );
            if($postdata['recordid']){
                if(!$record_rs = $obj_order_record->find(array("id"=>$postdata['recordid'], "student_id"=>$this->login_rs["id"])))
                    throw new Exception("找不到当前预约，可能已被删除");
                if($record_rs["order_endtime"] < time())
                    throw new Exception("当前预约已超过了24小时，无法修改预约信息");
                if(!$obj_order_record ->update(array('id' =>$postdata['recordid']),$data)){
                    throw new Exception('修改课程预约失败，请稍后重试！');
                }
            }else{
                if(!$obj_order_record ->create($data)){
                    throw new Exception('预约课程失败，请稍后重试！');
                }
            }
            $redata['message']= '课程预约成功！';
            $this->returnApi($redata);

        }catch (Exception $e){
            echo json_encode(array("data" => array(), "message" => $e->getMessage(), "code" => '0'));
            exit();
        }
    }

    public function getReserve(){
        try{
            $redata = array();
            $postdata = $this->spArgs();
            $obj_order_record = spClass('order_record');
            $obj_school_week = spClass('school_week');
            $obj_course_time = spClass('course_time');
            $obj_cato_course = spClass('cato_course');

            //不展示今天之前的选课记录
            $where = 'sys_order_record.isdel = 0 and sys_order_record.student_id = ' .
                $this->login_rs['id'] . ' and days >=" '. date('Y-m-d', time()) .'"';
            $res_order_record = $obj_order_record ->findAll($where, 'days asc, time asc')   ;

            if(!empty($res_order_record)){
                foreach($res_order_record as $k =>&$v){
                    $course_name_info = $obj_course_time->find(array('id' => $v['time']),null,'id,name');
                    $school_week_info = $obj_school_week->find(array('id' => $v['school_week_id']),null,'id,name');
                    $cato_course_info = $obj_cato_course->find(array('id'=>$v['test_id'], 'status'=>1, 'isdel'=>0,'level_id'=>3));
                    $v['course_name'] = $course_name_info['name'];
                    $v['week_name'] = '第'.$school_week_info['name'].'教学周';
                    $v['test_name'] = $cato_course_info['name'];
                    if($v['order_status'] == 0){
                        if(time() > $v['order_starttime'] && time() < $v['order_endtime']){
                            $v['order_status'] = '0';
                            $v['order_statusText'] = '预约中';
                        }elseif(time() > $v['order_endtime'] && time() < strtotime($v['days'])){
                            $obj_order_record ->update(array('id'=>$v['id']), array('order_status' =>1));
                            $v['order_status'] = '1';
                            $v['order_statusText'] = '预约完成';
                        }elseif(time() > strtotime($v['days'])){
                            $obj_order_record ->update(array('id'=>$v['id']), array('order_status' =>3));
                            $v['order_status'] = '3';
                            $v['order_statusText'] = '已完成';
                        }
                    }elseif($v['order_status'] == 1){
                        $v['order_status'] = '1';
                        $v['order_statusText'] = '预约完成';
                    }elseif($v['order_status'] == 3){
                        $v['order_status'] = '3';
                        $v['order_statusText'] = '已完成';
                    }

                }
                unset($v);
            }
            echo json_encode(array("data"=>$res_order_record, "message"=>"success", "code"=>"1", 'totalCount'=>count($res_order_record)));
            exit();

        }catch(Exception $e){
            echo json_encode(array("data" => array(), "message" => $e->getMessage(), "code" => '0'));
            exit();
        }
    }

    public function getcurrent(){
        try{
            $postdata = $this->spArgs();
            if($postdata['date']){
                $date = date('Y-m-d', strtotime($postdata['date']));
            }else{
                $date = date('Y-m-d',time());
            }
            $obj_school_weeks = spClass('school_week');

            $current_school_week = $obj_school_weeks->find(array('status'=>1, 'isdel'=>0,'starttime <=' => $date, 'endtime >=' => $date ));
            if($current_school_week){
                echo json_encode(array("data"=>$current_school_week, "message"=>"success", "code"=>"1"));
                exit();
            }else{
                echo json_encode(array("data"=>array('is_weekend' => true), "message"=>"success", "code"=>"1"));
                exit();
            }
        }catch(Exception $e){
            echo json_encode(array("data" => array(), "message" => $e->getMessage(), "code" => '0'));
            exit();
        }


    }

    public function getReserveCount(){
        try{
            $redata = array();
            $obj_order_record = spClass('order_record');
            $where = array(
                'student_id' => $this->login_rs['id'],
                'days >= ' => date('Y-m-d', time()),
            );
            $redata['totalCount'] = $obj_order_record ->findCount($where);
            $this->returnApi($redata);
        }catch(Exception $e){
            echo json_encode(array("data" => array(), "message" => $e->getMessage(), "code" => '0'));
            exit();
        }
    }

}